import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Contacts } from '@ionic-native/contacts/ngx';
import * as pinyin from 'pinyin';
import { HttpService } from 'src/app/service/http.service';

interface ContactItem {
  letter: string;
  data: any[];
}

@Component({
  selector: 'app-contacts-mobile',
  templateUrl: './contacts-mobile.component.html',
  styleUrls: ['./contacts-mobile.component.scss'],
})
export class ContactsMobileComponent implements OnInit {

  contactUsers: ContactItem[] = [];

  constructor(private router: Router, private contacts: Contacts, private httpService: HttpService) {
    for (let i = 0; i < 26; i++) {
      this.contactUsers.push({ letter: String.fromCharCode(65 + i), data: [] })
    }
    this.contactUsers.push({ letter: '#', data: [] })
    this.getAllContacts()
  }

  ngOnInit() { }

  async getAllContacts() {
    // 获取手机通讯录中的联系人列表
    // 网上说有一个大坑（未测试，因为没有ios环境）：Android的全名显示在displayName，IOS的全名显示在name.formatted
    const mobileUsers = await this.contacts.find(['*'], { filter: '', multiple: true, hasPhoneNumber: true })
    const pattern = new RegExp('[^0-9]', 'gi')
    const telephones = new Set<string>()
    const telephoneUsers = {}
    for (const mobileUser of mobileUsers) {
      const displayName = mobileUser.displayName
      if (!displayName) {
        continue
      }
      for (const telphoneItem of mobileUser.phoneNumbers) {
        const value = telphoneItem.value
        if (value) {
          const telephone = value.replace(pattern, '')
          telephones.add(telephone)
          telephoneUsers[telephone] = displayName
        }
      }
    }

    // 根据手机通讯录中的电话号码，查找已注册的微信用户
    const searchResult = await this.httpService.getContactsBytelephone(Array.from(telephones))
    const wechatUsers = {}
    for (const dataItem of searchResult.data) {
      if (dataItem.telephone) {
        wechatUsers[dataItem.telephone] = dataItem
      }
    }

    // 根据名字分组
    for (const telephone in telephoneUsers) {
      const displayName = telephoneUsers[telephone]
      let letterIndex = 26;
      const letters = pinyin(displayName.charAt(0), { style: pinyin.STYLE_FIRST_LETTER })
      if (letters && letters[0] && letters[0][0]) {
        const letter = letters[0][0].charAt(0).toUpperCase()
        letterIndex = letter.charCodeAt() - 65
      }

      const wechatUser = wechatUsers[telephone]
      if (wechatUser) {
        wechatUser.displayName = displayName
        this.contactUsers[letterIndex].data.push(wechatUser)
      }
    }
  }

  addContact(contact) {
    if (!contact.isFriend) {
      this.router.navigate(['/contacts/contacts-apply', contact.id])
    }
  }
}
